<?php 

class Controller_Service extends Controller_Abstract
{
	function actionLanding()
	{
		$camid = $this->_context->cam;
		if (empty($camid))
		{
			header(Util::HTTPStatus(404));
			exit;
		}
		$model = new Media();
		$campaign = $model->getCampaignById($camid);
		if ($campaign == false)
		{
			header(Util::HTTPStatus(404));
			exit;
		}
		$cookie = $_COOKIE[Q::ini('landing_cookie_key')];
		if (empty($cookie))
		{
			$urls = $model->getLandingUrlsByOfferId($campaign['o_id']);
			if (count($urls)<1)
			{
				header(Util::HTTPStatus(404));
				exit;
			}
			$url = $this->getUrlByRandom($urls);
			setcookie(Q::ini('landing_cookie_key'), $url['id'], time()+60*60*24*$campaign['cookie_window'], '/', '' . COOKIE_DOMAIN, 0, 1);
		}
		else
		{
			$url = $model->getLandingUrlById($cookie);
		}
		header("Location: " . $url['url']);
		exit;
	}
	private function getUrlByRandom($urls)
	{
		$total = 0;
		$fromto = array();
		foreach($urls as $url)
		{
			$fromto[] = array('from' => $total, 'to' => $total+$url['weight'], 'url' => $url);
			$total += $url['weight'];
		}
		print_r($total);
		$rand = rand(0, $total-1);
		print_r($rand);
		foreach ($fromto as $value)
		{
			if ($rand >= $value['from'] && $rand < $value['to'])
			{
				return $value['url'];
			}
		}
	}
}
?>